package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.exception.BusinessException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageBean;
import com.sky.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    //分类分页
    @Override
    public PageBean findByPage(CategoryPageQueryDTO categoryPageQueryDTO) {
        //开启分页
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        //执行查询
        List<Category> list=categoryMapper.findList(categoryPageQueryDTO);
        Page<Category> page= (Page<Category>) list;
        //返回结果
        return new PageBean(page.getTotal(),page.getResult());
    }

    //新增分类
    @Override
    public void save(Category category) {
        //1.补齐参数
        category.setStatus(1);
        //2.调用mapper保存
        categoryMapper.save(category);
    }

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    //删除分类
    @Override
    public void deleteById(Long id) {
        int count  = dishMapper.countByCategoryId(id);
        if (count>0){
            throw new BusinessException("当前分类下存在菜品,无法删除");
        }
        int number=setmealMapper.countByCategoryId(id);
        if (number>0){
            throw new BusinessException("当前分类下存在套餐,无法删除");
        }
        //执行删除
        categoryMapper.deleteByid(id);

    }

    //分类回显
    @Override
    public Category findById(Long id) {
        return categoryMapper.findById(id);
    }

    //分类修改
    @Override
    public void update(Category category) {
        categoryMapper.update(category);
    }

    //根据类型查询
    @Override
    public List<Category> findByList(Integer type) {
        //1. 将参数封装到dto
        CategoryPageQueryDTO dto = new CategoryPageQueryDTO();
        dto.setType(type);

        //2. 调用查询方法
        List<Category> list = categoryMapper.findList(dto);
        return list;
    }

    //启动禁用
    @Override
    public void updateById(Category category) {
        categoryMapper.update(category);
    }

    //查询分类列表
    @Override
    public List<Category> findByStatusAndType(Integer type) {
        //封装dto
        CategoryDTO categoryDTO = CategoryDTO.builder()
                .status(1)
                .type(type)
                .build();
        return categoryMapper.findByStatusAndType(categoryDTO);
    }
}
